/**
 *  Copyright Matt Silbernagel 2010
 *  
 *	This file is part of MobilePrinting.
 *
 *	MobilePrinting is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MobilePrinting is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MobilePrinting.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.uc.labs.MobilePrinting.PrintUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.xml.sax.SAXException;

import static edu.uc.labs.MobilePrinting.Configurator.*;

/**
 * 
 * @author Matthew Silbernagel
 */
public class PrinterFinder {
	
	public static ArrayList<Printer> getList() {
		
		String printerFile = USERSPACE + XMLFILE;
		String s		   = USERSPACE + XMLVALIDATE;
		
		ArrayList<Printer> printers = null;
		try {
			PrinterParser parser = new PrinterParser();
			String fileToParse = printerFile;
			LOGGER.debug("The file to parse for building the printer list is "
					+ fileToParse);
			LOGGER.debug("But first I want to validate the XML");
			if(!PrinterValidator.validate( printerFile, s )){
				try {
					PrinterWriter writer = new PrinterWriter();
					writer.writeBlank();
					LOGGER.debug("Created the xml file");
				} catch (ParserConfigurationException e) {
					LOGGER.error("PrinterFinder.java: Unable to write the printers.xml file: " + e.toString());
				}
				setZone(null);
			} 			
			printers = parser.parse(fileToParse);
		} catch (SAXException ex) {
			LOGGER.debug(ex.toString());
		} catch (IOException ex) {
			LOGGER.debug(ex.toString());
		} catch (XPathExpressionException ex) {
			LOGGER.debug(ex.toString());
		} catch (ParserConfigurationException ex) {
			LOGGER.debug(ex.toString());
		}
		if (!printers.isEmpty()) {
			return printers;
		}
		return printers;

	}

	public static void buildEmptyXMLFile(File file) throws IOException {
		LOGGER.debug("Looks like the file " + file.getAbsolutePath()
				+ " isn't valid." + " Creating an empty XML file...");
		if (file.exists()){
			LOGGER.debug("Deleting the invalid XML");
			file.delete();
		}
		
		try {
			PrinterWriter writer = new PrinterWriter();
			writer.writeBlank();
			LOGGER.debug("Created the blank xml file");
		} catch (ParserConfigurationException e) {
			LOGGER.error("Unable to write the printers.xml file: " + e.toString());
		}
		
	}
}
